package com.le.sarrs.cms;

import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public abstract class ScheduledCheckMap<K, V> {

    private volatile Map<K, V> map;
    private CountDownLatch initializedSignal = new CountDownLatch(1);
    private ScheduledExecutorService updateExecutor;

    public ScheduledCheckMap(int interval, TimeUnit unit) {

        updateExecutor = Executors.newSingleThreadScheduledExecutor();
        updateExecutor.scheduleWithFixedDelay(createUpdateTask(), 0, interval, unit);
    }

    protected abstract Map<K, V> query();

    private Runnable createUpdateTask() {

        return new Runnable() {
            @Override
            public void run() {
                try {
                    setValue(query());
                } catch (Exception e) {
                } finally {
                    initializedSignal.countDown();
                }
            }
        };
    }

    public void setValue(Map<K, V> map) {
        this.map = map;
    }

    public int size() {
        return map.size();
    }

    public Map<K, V> getMap() {
        return this.map;
    }

    public boolean containsKey(K key) {
        return this.map.containsKey(key);
    }

    public V get(K key) {
        return map.get(key);
    }

}
